<?php

namespace App\Http\Controllers;

use App\Exceptions\InvalidRequestException;
use App\Models\OrderItem;
use App\Models\Product;
use Illuminate\Http\Request;

class ProductsController extends Controller
{
    //商品首页
    public function index(Request $request)
    {
        //$products = Product::query()->where('on_sale',true)->paginate(16);
        //创建一个查询构析器
        $builder = Product::query()->where('on_sale',true);

        if ($search = $request->input('search','')){
            $like = '%'.$search.'%';

            $builder->where(function ($query) use ($like){
                $query->where('title','like',$like)
                    ->orWhere('description','like',$like)
                    ->orWhereHas('skus',function ($query) use ($like){
                        $query->where('title','like',$like)
                            ->orWhere('description','like',$like);
                    });
            });
        }

        if ($order = $request->input('order','')){
            if (preg_match('/^(.+)_(asc|desc)$/',$order,$m)){
                if (in_array($m[1],['price','sold_count','rating'])){
                    $builder->orderBy($m[1],$m[2]);
                }
            }
        }

        $products = $builder->paginate(16);
        return view('products.index',[
            'products' => $products,
            'filters' => [
                'search' => $search,
                'order' => $order
            ]
            ]);
    }

    //商品详情
    public function show(Product $product ,Request $request){

        if (!$product->on_sale){
            throw new InvalidRequestException('商品未上架');
        }

        //判断是否收藏
        $favored = false;
        if ($user = $request->user()){
            $favored = boolval($user->favoriteProducts()->find($product->id));
        }

        //评价
        $reviews = OrderItem::query()
            ->with(['order.user', 'productSku']) // 预先加载关联关系
            ->where('product_id', $product->id)
            ->whereNotNull('reviewed_at') // 筛选出已评价的
            ->orderBy('reviewed_at', 'desc') // 按评价时间倒序
            ->limit(10) // 取出 10 条
            ->get();
       //var_dump($reviews);die();
        return view('products.show',[
            'product' => $product,
            'favored' => $favored,
            'reviews' => $reviews
        ]);
    }

    //收藏
    public function favor(Product $product,Request $request)
    {
        $user = $request->user();
        if ($user->favoriteProducts()->find($product->id)){//已经收藏,直接返回空
            return [];
        }

        $user->favoriteProducts()->attach($product);//关联
        return [];
    }

    //取消收藏
    public function disfavor(Product $product, Request $request)
    {
        $user = $request->user();
        $user->favoriteProducts()->detach($product);//取消关联

        return [];
    }

    //收藏商品列表
    public function favorites(Request  $request)
    {
        $products = $request->user()->favoriteProducts()->paginate(16);

        return view('products.favorites',['products' => $products]);
    }
}
